package com.tanhua.dubbo.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.domain.mysql.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo findById(Long id) {
        return userInfoMapper.selectById(id);
    }

    @Override
    public Map<Long, UserInfo> findByIds(Integer page, Integer pageSize, List<Long> ids, UserInfo userInfo) {
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(!BeanUtil.isEmpty(userInfo.getAge()), UserInfo::getAge, userInfo.getAge())
                .eq(!BeanUtil.isEmpty(userInfo.getGender()), UserInfo::getGender, userInfo.getGender())
                .like(!BeanUtil.isEmpty(userInfo.getNickname()), UserInfo::getNickname, userInfo.getNickname())
                .in(!CollUtil.isEmpty(ids), UserInfo::getId, ids);
        userInfoMapper.selectPage(userInfoPage, queryWrapper);
        List<UserInfo> records = userInfoPage.getRecords();
        Map<Long, UserInfo> map = records.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
        return map;
    }

    @Override
    public IPage<UserInfo> findAll(Integer page, Integer pagesize) {
        return userInfoMapper.selectPage(new Page<>(page, pagesize), null);
    }
}